﻿using OznerOA.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OznerOA.BLL.Workflow.Request
{
    public class RequestBaseBLL : BaseBLL
    {
        Dictionary<string, string> urlTablestring = new Dictionary<string, string>();
        private string pageId = "Wf:pendingMatters";
        protected BaseResult<List<OznerOA.Model.Workflow>> GetAllWorkflow(string URL, int page)
        {
            BaseResult<List<OznerOA.Model.Workflow>> brRes = null;
            List<Model.Workflow> flows = new List<Model.Workflow>();
            if (!urlTablestring.ContainsKey(URL))
            {
                BaseResult<List<OznerOA.Model.Workflow>> br = GetLoginedDocument<List<OznerOA.Model.Workflow>>(URL);
                if (br.Code == Code.OK)
                {
                    //从br.html中获取tableString
                    int tableStringIndex = br.HttpBaseResult.Html.IndexOf("__tableStringKey__");
                    if (tableStringIndex > 0)
                    {
                        //获取TableString
                        logBLL.Debug("__tableStringKey__索引:{0}", tableStringIndex);
                        string tablestring = br.HttpBaseResult.Html.Substring(tableStringIndex + "__tableStringKey__".Length + 2);
                        tablestring = tablestring.Substring(0, tablestring.IndexOf("'"));
                        urlTablestring.Add(URL, tablestring);
                    }
                    else
                    {
                        brRes = GetResult<List<Model.Workflow>>(Code.NULL, "获取已办事宜失败", "请求结果中未查询到[__tableStringKey__]信息!");
                    }
                }

            }

            if (urlTablestring.ContainsKey(URL))
            {
                //使用pageid和tableString发送请求
                string url = string.Format(
                "/weaver/weaver.common.util.taglib.SplitPageXmlServlet?tableInstanceId=&tableString={0}&pageIndex={1}&orderBy=null&otype=null&mode=run&customParams=null&selectedstrs=&pageId={2}"
                , urlTablestring[URL], page, pageId);
                brRes = GetLoginedDocument<List<Model.Workflow>>(url);
                if (brRes.Code == Code.OK && brRes.HttpBaseResult.Html != null)
                {
                    HtmlAgilityPack.HtmlDocument docTable = new HtmlAgilityPack.HtmlDocument();
                    docTable.LoadHtml(brRes.HttpBaseResult.Html);
                    HtmlAgilityPack.HtmlNodeCollection hnHeads = docTable.DocumentNode.SelectNodes("//head");
                    int rowHead = hnHeads == null ? 1 : hnHeads.Count;
                    if (rowHead > 0)
                    {
                        HtmlAgilityPack.HtmlNodeCollection hns = docTable.DocumentNode.SelectNodes("//row");
                        if (hns != null && hns.Count > 0)
                        {
                            for (int i = 1; i <= hns.Count; i++)
                            {
                                //封装Workflow对象
                                Model.Workflow flow = GetWorkflow(docTable, "//row[" + i + "]");
                                //对没有flowid的再次查询
                                if (string.IsNullOrEmpty(flow.FlowId))
                                {
                                    //请求流程详细页面
                                    string urlDetail = string.Format("/workflow/request/ViewRequest.jsp?requestid={0}&_workflowid={1}&_workflowtype=&isovertime=0",
                                        flow.Requestid, flow.WorkflowId);
                                    BaseResult<object> brDetail = GetLoginedDocument<object>(urlDetail);
                                    if(brDetail.Code == Code.OK)
                                    {
                                        HtmlAgilityPack.HtmlDocument doc = brDetail.OtherInfo as HtmlAgilityPack.HtmlDocument;
                                        HtmlAgilityPack.HtmlNode hn = doc.DocumentNode.SelectSingleNode("//span[@id='objName']");
                                        if(hn != null)
                                        {
                                            string innerText = hn.InnerText;
                                            if (!string.IsNullOrEmpty(innerText))
                                            {
                                                flow.FlowId = innerText.Substring(innerText.LastIndexOf(" ") + 1);
                                            }
                                        }
                                    }
                                }
                                //查询flowId
                                flows.Add(flow);
                            }
                        }
                    }
                    else
                    {
                        brRes = GetResult<List<Model.Workflow>>(Code.NULL, "获取已办事宜失败", "请求结果失败!");
                    }
                }
            }else
            {
                brRes = GetResult<List<Model.Workflow>>(Code.NULL, "获取已办事宜失败", "获取TableString失败!");
            }
            brRes.Object = flows;
            return brRes;
        }
        protected Model.Workflow GetWorkflow(HtmlAgilityPack.HtmlDocument doc,string rowXPath)
        {
            Model.Workflow flow = new Model.Workflow();
            HtmlAgilityPack.HtmlNode hnRow = doc.DocumentNode.SelectSingleNode(rowXPath);
            if (hnRow != null)
            {
                //获取outhtml
                string rowHtml = hnRow.OuterHtml;


                string pathId = rowXPath + "/col[1]";
                string pathRequestName = rowXPath + "/col[@column='requestname']";
                string pathWorkflowid = rowXPath + "/col[@column='workflowid']";
                string pathCreater = rowXPath + "/col[@column='creater']";
                string pathReceivedate = rowXPath + "/col[@column='receivedate']";
                string pathCreatedate = rowXPath + "/col[@column='createdate']";
                string pathCurrentnodeid = rowXPath + "/col[@column='currentnodeid']";
                string pathRequestid = rowXPath + "/col[@column='requestid']";
                HtmlAgilityPack.HtmlNode hnId = doc.DocumentNode.SelectSingleNode(pathId);
                HtmlAgilityPack.HtmlNode hnRequestName = doc.DocumentNode.SelectSingleNode(pathRequestName);
                HtmlAgilityPack.HtmlNode hnWorkflowid = doc.DocumentNode.SelectSingleNode(pathWorkflowid);
                HtmlAgilityPack.HtmlNode hnCreater = doc.DocumentNode.SelectSingleNode(pathCreater);
                HtmlAgilityPack.HtmlNode hnCreatedate = doc.DocumentNode.SelectSingleNode(pathCreatedate);
                HtmlAgilityPack.HtmlNode hnReceivedate = doc.DocumentNode.SelectSingleNode(pathReceivedate);
                HtmlAgilityPack.HtmlNode hnCurrentnodeid = doc.DocumentNode.SelectSingleNode(pathCurrentnodeid);
                HtmlAgilityPack.HtmlNode hnRequestid = doc.DocumentNode.SelectSingleNode(pathRequestid);
                if (hnId != null)
                {
                    if (hnId.Attributes.Contains("showvalue"))
                    {
                        flow.ID = hnId.Attributes["showvalue"].Value;
                    }
                    if (hnId.Attributes.Contains("linkvalue"))
                    {
                        flow.ID = hnId.Attributes["linkvalue"].Value;
                    }
                }
                if (hnRequestName != null)
                {
                    flow.RequestName = hnRequestName.Attributes["value"].Value;
                }
                if (hnWorkflowid != null)
                {
                    string findStr = hnWorkflowid.OuterHtml + "<![CDATA[";
                    int indexWorkflowName = rowHtml.IndexOf(findStr);
                    if (indexWorkflowName >= 0)
                    {
                        string right = rowHtml.Substring(indexWorkflowName + findStr.Length);
                        flow.WorkflowName = right.Substring(0, right.IndexOf("]]"));
                    }

                    flow.WorkflowId = hnWorkflowid.Attributes["value"].Value;
                }
                if (hnCreater != null)
                {
                    string findStr = hnCreater.OuterHtml + "<![CDATA[";
                    int indexCreater = rowHtml.IndexOf(findStr);
                    if (indexCreater >= 0)
                    {
                        string right = rowHtml.Substring(indexCreater + findStr.Length);
                        flow.Creater = right.Substring(0, right.IndexOf("]]"));
                        flow.Creater = flow.Creater.Substring(flow.Creater.IndexOf(">") + 1);
                    }
                }
                if (hnReceivedate != null)
                {
                    string findStr = hnReceivedate.OuterHtml + "<![CDATA[";
                    int indexReceivedate = rowHtml.IndexOf(findStr);
                    if (indexReceivedate >= 0)
                    {
                        string right = rowHtml.Substring(indexReceivedate + findStr.Length);
                        flow.Receivedate = right.Substring(0, right.IndexOf("]]"));
                    }
                }
                if (hnCreatedate != null)
                {
                    string findStr = hnCreatedate.OuterHtml + "<![CDATA[";
                    int indexCreatedate = rowHtml.IndexOf(findStr);
                    if (indexCreatedate >= 0)
                    {
                        string right = rowHtml.Substring(indexCreatedate + findStr.Length);
                        flow.Createdate = right.Substring(0, right.IndexOf("]]"));
                    }
                }
                if (hnCurrentnodeid != null)
                {
                    flow.Currentnodeid = hnCurrentnodeid.Attributes["value"].Value;

                    string findStr = hnCurrentnodeid.OuterHtml + "<![CDATA[";
                    int indexCurrentnodeName = rowHtml.IndexOf(findStr);
                    if (indexCurrentnodeName >= 0)
                    {
                        string right = rowHtml.Substring(indexCurrentnodeName + findStr.Length);
                        flow.Currentnodename = right.Substring(0, right.IndexOf("]]"));
                    }
                }
                if (hnRequestid != null)
                {
                    flow.Requestid = hnRequestid.Attributes["value"].Value;
                    string findStr = hnRequestid.OuterHtml + "<![CDATA[<div id='";
                    int indexRequestDivId = rowHtml.IndexOf(findStr);
                    if (indexRequestDivId >= 0)
                    {
                        string right = rowHtml.Substring(indexRequestDivId + findStr.Length);
                        flow.RequestDivId = right.Substring(0, right.IndexOf("'"));
                    }
                }
                //流水号
                string str = "（流水号:";
                int indexFlowId = rowHtml.IndexOf(str);
                if (indexFlowId < 0)
                {
                    str = "（流程编号:";
                    indexFlowId = rowHtml.IndexOf(str);
                }
                if (indexFlowId >= 0)
                {
                    string flowId = rowHtml.Substring(indexFlowId + str.Length);
                    int ind = flowId.IndexOf("）");
                    flow.FlowId = flowId.Substring(0, ind);
                }
            }
            return flow;
        }
        /// <summary>
        /// 获取流程未操作者
        /// </summary>
        /// <returns></returns>
        public BaseResult<string> GetWorkflowUnoperatorPersons(Model.Workflow flow)
        {
            string URL = "http://oa.ozner.net:8080/workflow/search/WorkflowUnoperatorPersons.jsp";
            string postData = string.Format("requestid={0}&returntdid={1}"
                , flow.Requestid, flow.RequestDivId);
            BaseResult<string> br = GetLoginedDocument<string>(URL+"?"+postData);
            if(br.Code == Code.OK)
            {
                br.Object = br.HttpBaseResult.Html;
            }
            return br;
        }


    }
}
